package hku.cs.lunuo.tools;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

public class DirTools {

	public static String SEPERATOR = "/";
	public static char SEPERATORCHAR = '/';

	public static boolean delete(File path) {
		if (!path.exists())
			return true;
		if (path.isFile()) {
			return path.delete();
		}
		File[] files = path.listFiles();
		for (int i = 0; i < files.length; i++) {
			delete(files[i]);
		}
		return path.delete();
	}

	public static boolean delete(String path) {
		return delete(new File(path));
	}

	public static File prepare(File path) {
		return prepare(path.getAbsolutePath());
	}

	public static File prepare(String path) {
		if ("/".equals(path))
			return null;
		File f = new File(path);
		if (!f.exists())
			f.mkdirs();
		else if (!f.isDirectory()) {
			f.delete();
			f.mkdirs();
		}
		return f;
	}

	public static File newTest(String path) {
		if ("/".equals(path))
			return null;

		File f = new File(path);

		while (!delete(f)) {
			if (f.exists() && f.isDirectory() && f.list().length == 0)
				break;
		}
		f.mkdirs();
		return f;
	}

	public static void copy(File p, File f) throws Exception{
		FileInputStream fis = new FileInputStream(p);
		FileOutputStream fos = new FileOutputStream(f);
		byte[] buf = new byte[1024];
		int i = 0;
		while ((i = fis.read(buf)) != -1) {
			fos.write(buf, 0, i);
		}
		fis.close();
		fos.close();
	}
	
	public static void copyDir(File dira, File dird) throws Exception {
		if(dira.exists()&&dira.isDirectory()) {
			File[] fs = dira.listFiles();
			for(File f : fs) {
				if(f.isFile())
					copy(f, new File(dird, f.getName()));
				else {
					File xx = new File(dird, f.getName());
					xx.mkdir();
					copyDir(f, xx);
				}
			}
		}
	}

}
